<template>
  <div class="datetime-picker">
    <input
      type="datetime-local"
      v-model="internalValue"
      @change="handleDateTimeChange"
    />
    <div class="formatted-date">当前选择: {{ formattedDateTime }}</div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const internalValue = ref(''); // 用于绑定datetime-local输入的值
    const formattedDateTime = ref(''); // 用于显示格式化后的时间

    // 获取当前时间并设置默认值
    const setCurrentDateTime = () => {
      const now = new Date();
      
      // 转换为YYYY-MM-DD HH:mm:ss格式
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      // const seconds = String(now.getSeconds()).padStart(2, '0');
      
      // 设置显示值
      // formattedDateTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      formattedDateTime.value = `${year}-${month}-${day} ${hours}:${minutes}`;
      
      // 设置input的值（需要转换为YYYY-MM-DDTHH:mm格式）
      internalValue.value = `${year}-${month}-${day}T${hours}:${minutes}`;
    };

    // 处理日期时间变化
    const handleDateTimeChange = () => {
      if (!internalValue.value) return;
      
      const date = new Date(internalValue.value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      formattedDateTime.value = `${year}-${month}-${day} ${hours}:${minutes}`;
    };

    onMounted(() => {
      setCurrentDateTime();
    });

    return {
      internalValue,
      formattedDateTime,
      handleDateTimeChange
    };
  }
};
</script>

<style>
.datetime-picker {
  font-family: Arial, sans-serif;
  max-width: 400px;
  margin: 20px;
}

input[type="datetime-local"] {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
}

.formatted-date {
  margin-top: 10px;
  font-size: 14px;
  color: #555;
}
</style>